package name.luoyong.shiro.shiroIniCustom.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;

public abstract class AbstractFilter implements Filter {
	
	protected static DefaultWebSecurityManager defaultWebSecurityManager = null;
	protected static CacheManager cacheManager = null;
	protected static SessionManager sessionManager = null;

	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException,
			ServletException {
		initParam();
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		
		
		doFilter(request, response, chain);
		
	}

	public void init(FilterConfig arg0) throws ServletException {
	}
	
	private void initParam() {
		if(defaultWebSecurityManager != null) {
			return;
		}
		
		SecurityManager securityManager = SecurityUtils.getSecurityManager();
		if(securityManager == null) {
			return;
		}
		
		defaultWebSecurityManager = (DefaultWebSecurityManager) securityManager;
		cacheManager = defaultWebSecurityManager.getCacheManager();
		sessionManager = defaultWebSecurityManager.getSessionManager();
	}
	
	protected abstract void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) 
			throws IOException, ServletException;
	
}
